package com.xnx3.wangmarket.plugin.innerAccount.controller.admin;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.DateUtil;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.admin.util.AliyunLog;
import com.xnx3.wangmarket.plugin.base.controller.BasePluginController;
import com.xnx3.wangmarket.plugin.innerAccount.Global;
import com.xnx3.wangmarket.plugin.innerAccount.entity.DepartmentUser;

/**
 * 子账号管理
 * @author 管雷鸣
 */
@Controller
@RequestMapping("/plugin/innerAccount/admin/account/")
public class AccountInnerAccountPluginController extends BasePluginController {

	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;

	/**
	 * 账号列表
	 */
	@RequestMapping("list${url.suffix}")
	public String list(HttpServletRequest request, Model model){
		if(!haveSuperAdminAuth()){
			return error(model, "无权使用");
		}
		
		AliyunLog.addActionLog(getSiteId(), "查看子账号列表");
		
		Sql sql = new Sql(request);
		sql.setSearchColumn(new String[]{"username"});
		sql.appendWhere("user.authority = '"+Global.account_authority+"'");
	    //查询user数据表的记录总条数。 传入的user：数据表的名字为user
	    int count = sqlService.count("user", sql.getWhere());
	    //创建分页，并设定每页显示25条
	    Page page = new Page(count, 25, request);
	    //创建查询语句，只有SELECT、FROM，原生sql查询。其他的where、limit等会自动拼接
	    sql.setSelectFromAndPage("SELECT user.*,plugin_inneraccount_department_user.department_id FROM user LEFT JOIN plugin_inneraccount_department_user ON user.id = plugin_inneraccount_department_user.userid", page);
	    sql.setDefaultOrderBy("user.id DESC");
	    //因只查询的一个表，所以可以将查询结果转化为实体类，用List接收。
	    List<Map<String,Object>> list = sqlService.findMapBySql(sql);
	    
	    //将展示的列表数据记录传到页面以供显示
	    model.addAttribute("list", list);
	    //将分页信息传到页面以供显示底部分页
	    model.addAttribute("page", page);
		return "plugin/innerAccount/admin/account/list";
	}
	

	/**
	 * 添加、编辑
	 * @param id 若传入值，则是修改；若是0，则是新增
	 * @return
	 */
	@RequestMapping("edit${url.suffix}")
	public String edit(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value = "id", required = false , defaultValue="0") int id){
		if(!haveSuperAdminAuth()){
			return error(model, "无权使用");
		}
		
		User user;
		if(id>0){
			//编辑
			user = sqlService.findById(User.class, id);
			if(user == null){
				return error(model, "要修改的用户不存在");
			}
			//查询用户所属的部门
			DepartmentUser departmentUser = sqlService.findAloneByProperty(DepartmentUser.class, "userid", user.getId()); 
			if(departmentUser == null){
				return error(model, "该用户所属部门不存在！");
			}
			model.addAttribute("departmentUser", departmentUser);
		}else{
			user = new User();
		}
		
		model.addAttribute("user", user);
		return "plugin/innerAccount/admin/account/edit";
	}
	
	/**
	 * 保存
	 * @param departmentId 当前账号所属的部门
	 */
	@RequestMapping(value="save${url.suffix}", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO save(User userInput,
			HttpServletRequest request,Model model,
			@RequestParam(value = "departmentList", required = false , defaultValue="0") int departmentId){
		if(!haveSuperAdminAuth()){
			return error("无权使用");
		}
		if(departmentId == 0){
			return error("请选择用户所属部门");
		}
		
		User user;
		if(userInput.getId() == null || userInput.getId() == 0 ){
			//新增
			user = new User();
			user.setAuthority(Global.account_authority);
			user.setUsername(userInput.getUsername());
			user.setPassword(userInput.getPassword());
			user.setNickname(userInput.getNickname());
			user.setLasttime(DateUtil.timeForUnix10());
			BaseVO vo = userService.createUser(user, request);
			
			//如果失败，那么直接把它返回
			if(vo.getResult() - BaseVO.FAILURE == 0){
				return vo;
			}
			
			//增加账号所属部门关联
			DepartmentUser departmentUser = new DepartmentUser();
			departmentUser.setUserid(user.getId());
			departmentUser.setDepartmentId(departmentId);
			sqlService.save(departmentUser);
		}else{
			//修改
			user = sqlService.findById(User.class, userInput.getId());
			if(user == null){
				return error("要修改的用户不存在");
			}
			user.setUsername(userInput.getUsername());
			user.setNickname(userInput.getNickname());
			sqlService.save(user);
			
			//修改账号所属部门的关联
			DepartmentUser departmentUser = sqlService.findAloneByProperty(DepartmentUser.class, "userid", user.getId());
			if(departmentUser == null){
				departmentUser = new DepartmentUser();
				departmentUser.setUserid(user.getId());
			}
			departmentUser.setDepartmentId(departmentId);
			sqlService.save(departmentUser);
		}
		
		
		return success();
	}
	
	/**
	 * 用户删除
	 * @param id 要删除的用户的id
	 * @return
	 */
	@RequestMapping(value="delete${url.suffix}", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO delete(HttpServletRequest request,Model model,
			@RequestParam(value = "id", required = false , defaultValue="0") int id){
		if(!haveSuperAdminAuth()){
			return error("无权使用");
		}
		if(id < 1){
			return error("您要删除哪个用户呢？");
		}
		User user = sqlService.findById(User.class, id);
		if(user == null){
			return error("要删除的用户不存在");
		}
		
		sqlService.delete(user);
		
		
		return success();
	}
	
}